package com.waverider.promotion.biz.manager;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.springframework.beans.factory.InitializingBean;

import com.iacrqq.util.FileUtil;

/**
 * 
 * @author sihai
 *
 */
public class TemplateManager implements InitializingBean
{
	private Map<String, String> templateMap;
	private Map<String, String> templateStringMap;
	private VelocityEngine velocityEngine;
	
	private void _init_() throws Exception
	{
		velocityEngine = new VelocityEngine();
		velocityEngine.addProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");          // 输入编码格式设置
//        velocityEngine.addProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");         // 输出编码格式设置

		velocityEngine.init();
		
		templateStringMap = new HashMap<String, String>();
		
		for(Map.Entry<String, String> entry : templateMap.entrySet())
		{
			templateStringMap.put(entry.getKey(), FileUtil.read4String(this.getClass().getClassLoader().getResource(entry.getValue()).getFile()));
		}
	}
	
	public String getHTML(String key, Map<String, Object> context) throws Exception
	{
		StringWriter writer = new StringWriter();
		VelocityContext vContext = new VelocityContext();
		for(Map.Entry<String, Object> entry : context.entrySet())
		{
			vContext.put(entry.getKey(), entry.getValue());
		}
		velocityEngine.evaluate(vContext, writer, key, templateStringMap.get(key));
		
		return writer.toString();
	}
	
	public void close() throws Exception
	{
		templateMap.clear();
		templateStringMap.clear();
	}
	
	@Override
	public void afterPropertiesSet() throws Exception
	{
		_init_();
	}
	
	public void setTemplateMap(Map<String, String> templateMap)
	{
		this.templateMap = templateMap;
	}
}
